package org.kernely.stream.messageFilter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.kernely.stream.service.StreamFilter;

public class LinkFilter implements StreamFilter{

	public String applyFilter(String messageToFilter) {
		String txt = messageToFilter;
		String regexp = "(^<.*>)?(((f|ht){1}tp[s]?:\\/\\/|(?<!\\S)www\\.)[-a-zA-Z0-9@:%_\\+.~#?&\\/\\/=]+)(^</.*>)?\\b";

		Pattern p = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(txt);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			String link = m.group(2);
			if(!link.startsWith("http://")){
				link = "http://" + link;
			}
			m.appendReplacement(sb, "<a href=\"" + link + "\" target=\"_blank\"> "+ link +"</a>");
		}
		m.appendTail(sb);
		
		return sb.toString();
	}

}
